package com.zhen;

import com.zhen.domain.Article;
import com.zhen.domain.Order;
import com.zhen.domain.User;
import com.zhen.mapper.OrderMapper;
import com.zhen.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class ManyToManyTest {

    public static void main(String[] args) throws IOException {
        InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        ManyToManyTest manyToManyTest = new ManyToManyTest();
        manyToManyTest.testSelectUserById(session);
        manyToManyTest.testSelectOrderById(session);
        session.commit();
        session.close();
    }


    public void testSelectUserById(SqlSession session){
        UserMapper userMapper = session.getMapper(UserMapper.class);
        User user = userMapper.selectUserById(1);
        System.out.println(user.getId() + "  " + user.getUsername());
        List<Order> orderList = user.getOrders();
        for(Order order : orderList){
            System.out.println(order);
        }
    }

    public void testSelectOrderById(SqlSession session){
        OrderMapper orderMapper = session.getMapper(OrderMapper.class);
        Order order = orderMapper.selectOrderById(2);
        System.out.println(order.getId() + " " + order.getCode() + " " + order.getTotal());
        User user = order.getUser();
        System.out.println(user);
        List<Article> articles = order.getArticles();
        for(Article article : articles){
            System.out.println(article);
        }
    }
}
